package org.bing.zion.core;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class PerformerPool {
	private Executor executor;
	private Performer[] pool;

	private int point = 0;

	public PerformerPool(int num) {
		if (num <= 0) {
			return;
		}
		executor = Executors.newFixedThreadPool(num);
		pool = new Performer[num];
		for (int i = 0; i < num; i++) {
			pool[i] = new Performer();
			startup(i, pool[i]);
		}
	}

	public void perform(Session session, Object msg) {
		nextPerformer().perform(session, msg);
	}

	public int totalQueueSize() {
		int size = 0;
		for (int i = 0; i < pool.length; i++) {
			size += pool[i].queueSize();
		}
		return size;
	}

	public void startup(final int no, final Performer p) {
		executor.execute(new Runnable() {
			public void run() {
				Thread.currentThread().setName("seda-performer-" + no);
				p.run();
			}
		});
	}

	private synchronized Performer nextPerformer() {
		// TODO impl load tuning stragy
		point++;
		if (point > pool.length - 1) {
			point = 0;
		}
		return pool[point];
	}
}
